package Email

import (
	Redis "GoDance/webserver/redis"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"net/smtp"
	"time"
)

func SendEmail() func(c *gin.Context) {
	return func(c *gin.Context) {
		//smtp.PlainAuth()
		// 参数1：Usually identity should be the empty string, to act as username
		// 参数2：username
		//参数3：password
		//参数4：host
		email := c.PostForm("email")
		auth := smtp.PlainAuth("", "1739466630@qq.com", "pwabuxdsvxofcibd", "smtp.qq.com")
		to := []string{email}
		//发送随机数为验证码
		rand.Seed(time.Now().Unix())
		num := rand.Intn(10000)
		//发送内容使用base64 编码，单行不超过80字节，需要插入\r\n进行换行
		str := fmt.Sprintf("From:1739466630@qq.com\r\nTo:"+email+"\r\nSubject:verifycode\r\n\r\n %d \r\n", num) //邮件格式
		msg := []byte(str)
		err := smtp.SendMail("smtp.qq.com:587", auth, "1739466630@qq.com", to, msg)
		if err != nil {
			fmt.Println(err)
			c.JSON(http.StatusNotFound, gin.H{
				"status":  404,
				"message": "邮箱错误",
			})
			return
		}
		Redis.Save_code(email, num)
		c.JSON(http.StatusOK, gin.H{
			"status": 200,
		})
	}
}
